package top.codecrab.springcloud.controller;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.codecrab.springcloud.entity.Payment;
import top.codecrab.springcloud.entity.response.Result;
import top.codecrab.springcloud.lb.LoadBalancer;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author codecrab
 * @since 2021年05月14日 10:40
 */
@Slf4j
@RestController
@RequestMapping("/consumer/payment")
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/payment";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancer loadBalancer;

    @GetMapping("/save")
    public Result save(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/save", payment, Result.class);
    }

    @GetMapping("/get/{id}")
    public Result getById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/get/" + id, Result.class);
    }

    @GetMapping("/lb")
    public String getPaymentLB() {

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if (CollectionUtil.isEmpty(instances)) {
            log.warn("服务列表为空");
            return null;
        }

        ServiceInstance instance = loadBalancer.instance(instances);
        return restTemplate.getForObject(instance.getUri() + "/payment/lb", String.class);
    }

    // ====================> zipkin+sleuth
    @GetMapping("/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/", String.class);
    }
}
